-- ======================================================================
-- Hell Lua Bus
-- 
-- Copyright 2012-2013Hell-Prototypes
--
-- http://www.hellprototypes.com/
--
-- This is free software, licensed under the terms of the GNU General
-- Public License as published by the Free Software Foundation.
-- ======================================================================
hlb = require('libhlb')

function device_open()
	local ret = hlb.usb_open(0x04B4FFFF)
	if ret < 0 then
		print("Fail to open usb device")
		return false
	end
	
	return true
end

function device_close()
	local ret = hlb.usb_close()
	if ret < 0 then
		print("Fail to close usb device")
		return false
	end
	
	return true
end

function pause()
    io.write("\r\nAny key to continue ...")
    io.flush()
    io.read()
    print("")
end
-- -----------------------------------------------
function send_ctrl_cmd(cmd_data)
    if type(cmd_data) ~= "table" then
        print("cmd_data must be table type")
        return false
    end

    local msg = {0x40, 0xb0, 0, 0, #cmd_data, 100}
    local ret

    if #cmd_data > 0 then
        ret = hlb.usb_control_msg(cmd_data, msg)
    else
        ret = hlb.usb_control_msg(msg)
    end
    
    if ret < 0 then
        print("send_ctrl_cmd() ret = " .. ret)
        return false
    end

    return true
end
-- -----------------------------------------------
ret = device_open()
if ret == false then
    print("device_open fail")
    return
end

cmd = {0x3F}
ret = send_ctrl_cmd(cmd)
if ret == false then
    print("send_ctrl_cmd() exec fail 0")
    return
end
print("Start FPGA App")

hlb.msdelay(500) --wait for reconfig

cmd = {0x00}
ret = send_ctrl_cmd(cmd)
if ret == false then
    print("send_ctrl_cmd() exec fail 1")
    return
end

cmd = {0x80, 0x00, 0x00, 0x00, 0x00}
ret = send_ctrl_cmd(cmd)
if ret == false then
    print("send_ctrl_cmd() exec fail 2")
    return
end

-- bulk read test
ret = hlb.usb_bulk_read(0x86, 0x04, 1000)
print("ret types: " .. type(ret))
if type(ret) == "number" then
    print(" ret = " .. ret)
end

if type(ret) == "table" then
    for i=1, #ret do
        --print("ret[" .. i .. "] = " .. ret[i])
        print(string.format("ret[%d] = 0x%02x", i, ret[i]))
    end
end

--[[
pause()

cmd = {0x80, 0x00, 0x00, 0x00, 0x3f}
ret = send_ctrl_cmd(cmd)
if ret == false then
    print("send_ctrl_cmd() exec fail 3")
    return
end

pause()

cmd = {0x80, 0x00, 0x00, 0x00, 0x00}
ret = send_ctrl_cmd(cmd)
if ret == false then
    print("send_ctrl_cmd() exec fail 4")
    return
end
--]]
device_close()
